using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Redis_demo.Services;
using StackExchange.Redis;
using  Redis_demo.Result;
using Redis_demo.utils;
using Redis_demo.Dtos;
using Microsoft.EntityFrameworkCore;
using Mapster;

namespace Redis_demo.Controllers;

[Route("api/[controller]")]
public class UserController : ControllerBase
{
    public readonly IConnectionMultiplexer _connectionMultiplexer;
    public readonly UserDbContext _dbContext;
    public readonly UserServices _userServices;
    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IHttpContextAccessor _httpContextAccessor;
    public UserController(ILogger<WeatherForecastController> logger,
         IConnectionMultiplexer connectionMultiplexer,
         UserDbContext dbContext,
         UserServices userServices,
         IHttpContextAccessor httpContextAccessor)
    {
        _logger = logger;
        _connectionMultiplexer = connectionMultiplexer;
        _dbContext = dbContext;
        _userServices = userServices;
        _httpContextAccessor = httpContextAccessor;
    }

    [HttpGet("phone")]
    public async Task<Result<string>> SendCode(string phone)
    {
        // 1第一步校验手机号
        if(!ValidatePhoneNumber(phone)){
            return Result<String>.Fail("手机号不正确");
        }
        // 2 第二步生成验证码
        var code = new Random().Next(1000, 9999);
        // 3 保存的Redis中
        var dataBase = _connectionMultiplexer.GetDatabase();
        await dataBase.HashSetAsync(RedisConstants.Login_Code_Key, new HashEntry[]{new HashEntry(phone,code)});
        await dataBase.KeyExpireAsync(RedisConstants.Login_Code_Key,DateTime.Now.AddMinutes(RedisConstants.Login_User_Til));
        // 4发送验证码 todo

        // 5返回结果
        return Result<string>.SuccessRT("成功");
    }

    [HttpPost("login")]
    public async Task<Result<string>> Login(LoginFormDto loginForm)
    {
        // 1第一步校验手机号
        if(!ValidatePhoneNumber(loginForm.Phone)){
            return Result<String>.Fail("手机号不正确");
        }
        // 2从redis中取code
        var dataBase = _connectionMultiplexer.GetDatabase();
        var code = await dataBase.HashGetAsync(RedisConstants.Login_Code_Key, loginForm.Phone);
        // 3判断code是否正确
        if(!code.Equals(loginForm.Code)){
            return Result<String>.Fail("验证码不正确");
        }
        // 4判断用户是否存在
        var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Phone == loginForm.Phone);
        if(user == null){
            // 5注册用户
            user = new Entities.User{Id="222",Phone=loginForm.Phone,Name="11"};
            await _dbContext.Users.AddAsync(user);
            await _dbContext.SaveChangesAsync();
        }
        // 6保存用户信息到token
        var token = Guid.NewGuid().ToString();
        var userDto = user.Adapt<UserDto>();
        var loginToken = RedisConstants.Login_User_Key + token;
        //var msp1 = userDto.Adapt<IList<HashEntry>>();
        var map = new HashEntry[]{new HashEntry("name",userDto.Name),new HashEntry("phone",userDto.Phone)};
        await dataBase.HashSetAsync(loginToken,map);
        await dataBase.KeyExpireAsync(loginToken,DateTime.Now.AddHours(RedisConstants.Login_User_Til));
        // 7返回的Response的header中添加token
        _httpContextAccessor.HttpContext.Response.Headers.Add("token",loginToken);
        // 7返回结果
        return Result<string>.SuccessRT(loginToken);
    }

    private bool ValidatePhoneNumber(string phoneNumber)
    {
        // 定义手机号的正则表达式
        string pattern = @"^1[3456789]\d{9}$";

        // 使用正则表达式进行匹配
        Regex regex = new Regex(pattern);
        return regex.IsMatch(phoneNumber);
    }

}
